package com.eclipse.training.extensions;

import java.util.ArrayList;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;

public class ExtensionParser {
	public static final String EXTENSION_ID = "com.eclipse.training.myextension"; //$NON-NLS-1$

	public static final String ELEM_EXECUTABLE = "executable"; //$NON-NLS-1$
	public static final String ATT_CLASS = "class"; //$NON-NLS-1$

	private static ExtensionParser instances;
	private ArrayList<IMyExtension> executables = new ArrayList<IMyExtension>();

	protected ExtensionParser() {
		for (IExtension extension : Activator.getDefault()
				.getExtensionsRegistry()) {
			IConfigurationElement config = getConfigElement(extension,
					ELEM_EXECUTABLE);

			LogManager.getLogger().logInfo(
					Messages.ExtensionParser_3);

			if (config != null) {
				try {
					Object executable = config
							.createExecutableExtension(ATT_CLASS);
					
					LogManager.getLogger().logInfo(
							Messages.ExtensionParser_4);

					if (executable != null
							&& executable instanceof IMyExtension)
						executables.add((IMyExtension) executable);
				} catch (CoreException e) {
					LogManager.getLogger().logError(e);
				}
			}
		}
	}

	public ArrayList<IMyExtension> getExecutables() {
		return executables;
	}

	private static IConfigurationElement getConfigElement(IExtension extension,
			String element) {
		IConfigurationElement[] configs = extension.getConfigurationElements();

		for (IConfigurationElement c : configs) {
			if (c.getName().equals(element))
				return c;
		}
		return null;
	}

	public static ExtensionParser getInstance() {
		if (instances == null)
			instances = new ExtensionParser();
		return instances;
	}
}
